package com.aboverock.module.shiro.util;

import com.aboverock.module.system.domain.User;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * The Class ShiroCacheUtil.
 *
 * @author Rock Wang
 */
public class ShiroCacheUtil {

    @Autowired
    private CacheManager cacheManagerAuto;

    private static String authenticationCacheName;

    private static String authorizationCacheName;

    private static CacheManager cacheManager;
    
    public ShiroCacheUtil(String authenticationCacheName, String authorizationCacheName) {
        ShiroCacheUtil.authenticationCacheName = authenticationCacheName;
        ShiroCacheUtil.authorizationCacheName = authorizationCacheName;
    }

    @PostConstruct
    public void init() {
        cacheManager = cacheManagerAuto;
    }

    public static String getAuthenticationCacheName() {
        return authenticationCacheName;
    }

    public static String getAuthorizationCacheName() {
        return authorizationCacheName;
    }

    public static Cache<Object, Object> getCache(String cacheName) {
        return cacheManager.getCache(cacheName);
    }

    public static Cache<Object, Object> getAuthecticationCache() {
        return getCache(authenticationCacheName);
    }

    public static Cache<Object, Object> getAuthorizationCache() {
        return getCache(authorizationCacheName);
    }

    public static void removeAuthecticationInfo(String loginName) {
        getAuthecticationCache().remove(loginName);
    }

    public static void removeAuthecticationInfo(List<User> users) {
        users.forEach(user -> getAuthecticationCache().remove(user.getLoginName()));
    }

    public static void removeAuthorizationInfo(String loginName) {
        getAuthorizationCache().remove(loginName);
    }

    public static void removeAuthorizationInfo(List<User> users) {
        users.forEach(user -> getAuthorizationCache().remove(user.getLoginName()));
    }

    // RealmSecurityManager realmSecurityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
    // Cache<Object, Object> cache = (Cache) realmSecurityManager.getCacheManager().getCache(authorizationCache);
}
